﻿#include"stdafx.h"
#ifdef LK_NETWORK_TCPNODE_
namespace LK {
	namespace Network {
		namespace Tcp {
			/**
			@brief 绑定指定的地址和端口*/
			void TcpNode::Bind(PString address, PString port) {
				AddressInfo af(address, port);
				const AddressElement &rf = af[0];
				SocketAddress const& sa = rf.GetSocketAddressRef();
				soc->Bind(sa);
			}
			/**
			@brief 绑定指定的端口*/
			void TcpNode::Bind(PString addrport) {
				PString addr, port;
				index_t idx = addrport.LastIndexOf(L':');
				if (idx == -1 || idx == 0 || addrport[idx - 1] == L':'){
					addr = addrport;
					port = L"0";
				}
				else{
					addr = addrport.Remove(idx);
					port = addrport.Remove(0, idx + 1);
				}
				return Bind(addr, port);
			}
			void TcpNode::Listen() {
				soc.Listen();
			}
			/**
			@brief 接收连接请求并返回套接字*/
			PSocket TcpNode::Accept() {
				return soc.Accept();
			}
			/**
			@brief 连接指定的IP和端口*/
			PSocket TcpNode::Connect(PString address, PString port) {
				AddressInfo af(address, port);
				SocketAddress const&sa= af[0].GetSocketAddressRef();
				soc->Connect(sa);
				return soc;
			}
			/**
			@brief 连接指定的IP和端口，返回一个可以用来发送数据的套接字对象代理*/
			PSocket TcpNode::Connect(PString addrport) {
				PString addr,port;
				index_t idx = addrport.LastIndexOf(L':');
				if (idx == -1 || idx==0 || addrport[idx-1]==L':')Throw<SocketException>(L"端口号异常");
				addr = addrport.Remove(idx);
				port = addrport.Remove(0, idx + 1);
				return Connect(addr, port);
			}
			/**
			@brief 关闭传输*/
			void TcpNode::Close() { soc->Close(); soc->Asign(SocketType::Stream, ProtocolType::TCP,AddressFamily::Unspecified); }
			/**
			@brief 构造函数*/
			TcpNode::TcpNode():soc(new Socket(SocketType::Stream,ProtocolType::TCP)) {}
		}
	}
}
#endif